package com.ynet.controller;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;

/**
 * <h1>利用servlet做转发，实现js跨域解决同源问题</h1>
 * 
 * 做前端开发，避免不了跨域这个问题，跨域具体什么概念，不赘述，博客里太多。简单说下，我们用js发请求，不管post还是get，
 * 如果发请求的对象和当前web页面不在同一域名下
 * ，浏览器的同源策略会限制发请求，也就是说，如果单独写个HTML，用js发远程请求，是发布出去的，浏览器会认为这是不安全的，js在这里能做的很有限。
 * 网上看了很多文章
 * ，只用js一直没解决这个问题，jQuery的Ajax据说可以，但是测试后发现不行，也许是浏览器版本的原因。有种方法是jsonp，但是好像需要服务器支持
 * ，我对服务器端程序了解的少，不懂。再就是script，动态的添加script标签，在src里面填要发的请求地址，但是很明显，只能以get方式发请求，
 * 那么post怎么办？反正折磨了很有一段时间，狠下心来，不用js去处理了，用java代码做中转，学过一点皮毛，参考一下网上代码，问题得以解决。
 * 
 * 其实分析起来问题很简单，servlet不难，tomcat去处理，很多细节我们不用关心，再就是用java发请求了，之前一直找错方向饶了不少弯路。
 * 
 * @author liuxin
 */
public class SendPack {

	/**
	 * 发送get请求 url?a=x&b=xx形式
	 * @throws IOException 
	 */
	public static String sendGet1(String url, HttpServletRequest request) throws IOException {
		//获取 request 中的流
		InputStream inputStream = request.getInputStream();

		DataOutputStream ds = null;

		String result = "";
		BufferedReader in = null;
		try {
			String urlName = url;

			System.out.println(urlName);
			URL resUrl = new URL(urlName);
			URLConnection urlConnection = resUrl.openConnection();
			// http的连接类
			HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
			
			urlConnection.setRequestProperty("accept", "*/*");
			urlConnection.setRequestProperty("connection", "Keep-Alive");
			urlConnection.setRequestProperty("Content-Type", "text/html; charset=UTF-8");
			urlConnection.setRequestProperty("Cache-Control", "no-cache");

			httpURLConnection.setDoOutput(true);
			ds = new DataOutputStream(httpURLConnection.getOutputStream());
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			while ((length = inputStream.read(buffer)) != -1) {
				ds.write(buffer, 0, length);
			}
			ds.flush();
			
			in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

		} catch (Exception e) {
			System.out.println("发送get请求失败" + e);
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {in.close();}
				if (ds != null) {ds.close();}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 发送get请求 url?a=x&b=xx形式
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlName = "";
			if (param.length() != 0) {
				urlName = url + "?" + param;
			} else
				urlName = url;

			System.out.println(urlName);
			URL resUrl = new URL(urlName);
			URLConnection urlConnec = resUrl.openConnection();
			urlConnec.setRequestProperty("accept", "*/*");
			urlConnec.setRequestProperty("connection", "Keep-Alive");
			// urlConnec.setRequestProperty("user-agent",
			// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			urlConnec.setRequestProperty("Content-Type", "text/html; charset="
					+ "UTF-8");
			urlConnec.setRequestProperty("Cache-Control", "no-cache");

			urlConnec.connect();
			// Map<String, List<String>> map = urlConnec.getHeaderFields();
			// for (String key : map.keySet()) {
			// System.out.println(key + "--->" + map.get(key));
			// } // 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					urlConnec.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送get请求失败" + e);
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println(result);
		return result;
	}

	/**
	 * 发送post请求
	 */
	public static String sendPost(String url, String param) {
		String result = "";
		PrintWriter out = null;
		BufferedReader in = null;
		try {
			URL resUrl = new URL(url);
			System.out.println(url);

			URLConnection urlConnec = resUrl.openConnection();
			urlConnec.setRequestProperty("accept", "*/*");
			urlConnec.setRequestProperty("connection", "Keep-Alive");
			urlConnec.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行
			urlConnec.setDoInput(true);
			urlConnec.setDoOutput(true);
			out = new PrintWriter(urlConnec.getOutputStream());
			out.print(param);// 发送post参数
			out.flush(); // 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					urlConnec.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("post请求发送失败" + e);
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println(result);
		return result;
	}

	public static void main(String[] args) {
		// String resultGet =
		// sendPost("http://lx760.eicp.net/Inmanage/queryDetail.do", "");
		String resultGet = sendPost(
				"http://127.0.0.1:8080/send-server/send/12.action", "");
		System.out.println(resultGet);
	}
}
